"""
Redis使用示例
演示如何在Flask应用中使用Redis
"""

from flask import Blueprint, jsonify, request
from app.utils.redis_utils import RedisUtils
from config.redis_config import RedisConfig

# 创建Redis示例蓝图
redis_example_bp = Blueprint('redis_example', __name__)


@redis_example_bp.route('/redis/ping', methods=['GET'])
def ping_redis():
    """测试Redis连接"""
    is_connected = RedisUtils.is_connected()
    return jsonify({
        'status': 'success' if is_connected else 'error',
        'message': 'Redis连接正常' if is_connected else 'Redis连接失败',
        'connected': is_connected
    })


@redis_example_bp.route('/redis/basic/set', methods=['POST'])
def redis_set():
    """设置键值对"""
    data = request.get_json()
    if not data or 'key' not in data or 'value' not in data:
        return jsonify({'status': 'error', 'message': '请提供key和value'}), 400
    
    key = data['key']
    value = data['value']
    timeout = data.get('timeout', RedisConfig.CACHE_DEFAULT_TIMEOUT)
    
    success = RedisUtils.set(key, value, timeout)
    return jsonify({
        'status': 'success' if success else 'error',
        'message': '设置成功' if success else '设置失败',
        'key': key,
        'value': value,
        'timeout': timeout
    })


@redis_example_bp.route('/redis/basic/get', methods=['GET'])
def redis_get():
    """获取键值"""
    key = request.args.get('key')
    if not key:
        return jsonify({'status': 'error', 'message': '请提供key'}), 400
    
    value = RedisUtils.get(key)
    exists = RedisUtils.exists(key)
    ttl = RedisUtils.ttl(key)
    
    return jsonify({
        'status': 'success',
        'key': key,
        'value': value,
        'exists': exists,
        'ttl': ttl
    })


@redis_example_bp.route('/redis/basic/delete', methods=['DELETE'])
def redis_delete():
    """删除键"""
    key = request.args.get('key')
    if not key:
        return jsonify({'status': 'error', 'message': '请提供key'}), 400
    
    success = RedisUtils.delete(key)
    return jsonify({
        'status': 'success' if success else 'error',
        'message': '删除成功' if success else '删除失败',
        'key': key
    })


@redis_example_bp.route('/redis/counter/incr', methods=['POST'])
def redis_incr():
    """计数器增加"""
    data = request.get_json()
    if not data or 'key' not in data:
        return jsonify({'status': 'error', 'message': '请提供key'}), 400
    
    key = data['key']
    amount = data.get('amount', 1)
    
    new_value = RedisUtils.incr(key, amount)
    return jsonify({
        'status': 'success' if new_value is not None else 'error',
        'key': key,
        'amount': amount,
        'new_value': new_value
    })


@redis_example_bp.route('/redis/hash/set', methods=['POST'])
def redis_hash_set():
    """设置哈希表"""
    data = request.get_json()
    if not data or 'name' not in data or 'mapping' not in data:
        return jsonify({'status': 'error', 'message': '请提供name和mapping'}), 400
    
    name = data['name']
    mapping = data['mapping']
    timeout = data.get('timeout', RedisConfig.CACHE_DEFAULT_TIMEOUT)
    
    success = RedisUtils.hset(name, mapping, timeout)
    return jsonify({
        'status': 'success' if success else 'error',
        'message': '设置成功' if success else '设置失败',
        'name': name,
        'mapping': mapping,
        'timeout': timeout
    })


@redis_example_bp.route('/redis/hash/get', methods=['GET'])
def redis_hash_get():
    """获取哈希表"""
    name = request.args.get('name')
    key = request.args.get('key')
    
    if not name:
        return jsonify({'status': 'error', 'message': '请提供name'}), 400
    
    if key:
        # 获取单个字段
        value = RedisUtils.hget(name, key)
        return jsonify({
            'status': 'success',
            'name': name,
            'key': key,
            'value': value
        })
    else:
        # 获取所有字段
        data = RedisUtils.hgetall(name)
        return jsonify({
            'status': 'success',
            'name': name,
            'data': data
        })


@redis_example_bp.route('/redis/list/push', methods=['POST'])
def redis_list_push():
    """向列表添加元素"""
    data = request.get_json()
    if not data or 'name' not in data or 'values' not in data:
        return jsonify({'status': 'error', 'message': '请提供name和values'}), 400
    
    name = data['name']
    values = data['values']
    position = data.get('position', 'left')  # left或right
    
    if not isinstance(values, list):
        values = [values]
    
    if position == 'left':
        new_length = RedisUtils.lpush(name, *values)
    else:
        new_length = RedisUtils.rpush(name, *values)
    
    return jsonify({
        'status': 'success' if new_length is not None else 'error',
        'name': name,
        'values': values,
        'position': position,
        'new_length': new_length
    })


@redis_example_bp.route('/redis/list/pop', methods=['POST'])
def redis_list_pop():
    """从列表弹出元素"""
    data = request.get_json()
    if not data or 'name' not in data:
        return jsonify({'status': 'error', 'message': '请提供name'}), 400
    
    name = data['name']
    position = data.get('position', 'left')  # left或right
    
    if position == 'left':
        value = RedisUtils.lpop(name)
    else:
        value = RedisUtils.rpop(name)
    
    return jsonify({
        'status': 'success',
        'name': name,
        'position': position,
        'value': value
    })


@redis_example_bp.route('/redis/list/range', methods=['GET'])
def redis_list_range():
    """获取列表范围内的元素"""
    name = request.args.get('name')
    if not name:
        return jsonify({'status': 'error', 'message': '请提供name'}), 400
    
    start = int(request.args.get('start', 0))
    end = int(request.args.get('end', -1))
    
    values = RedisUtils.lrange(name, start, end)
    length = RedisUtils.llen(name)
    
    return jsonify({
        'status': 'success',
        'name': name,
        'start': start,
        'end': end,
        'values': values,
        'length': length
    })


@redis_example_bp.route('/redis/set/add', methods=['POST'])
def redis_set_add():
    """向集合添加元素"""
    data = request.get_json()
    if not data or 'name' not in data or 'values' not in data:
        return jsonify({'status': 'error', 'message': '请提供name和values'}), 400
    
    name = data['name']
    values = data['values']
    
    if not isinstance(values, list):
        values = [values]
    
    added_count = RedisUtils.sadd(name, *values)
    return jsonify({
        'status': 'success' if added_count is not None else 'error',
        'name': name,
        'values': values,
        'added_count': added_count
    })


@redis_example_bp.route('/redis/set/members', methods=['GET'])
def redis_set_members():
    """获取集合中的所有成员"""
    name = request.args.get('name')
    if not name:
        return jsonify({'status': 'error', 'message': '请提供name'}), 400
    
    members = RedisUtils.smembers(name)
    return jsonify({
        'status': 'success',
        'name': name,
        'members': list(members),
        'count': len(members)
    })


@redis_example_bp.route('/redis/set/member', methods=['POST'])
def redis_set_member():
    """检查元素是否在集合中"""
    data = request.get_json()
    if not data or 'name' not in data or 'value' not in data:
        return jsonify({'status': 'error', 'message': '请提供name和value'}), 400
    
    name = data['name']
    value = data['value']
    
    is_member = RedisUtils.sismember(name, value)
    return jsonify({
        'status': 'success',
        'name': name,
        'value': value,
        'is_member': is_member
    })


@redis_example_bp.route('/redis/object/set', methods=['POST'])
def redis_object_set():
    """存储对象"""
    data = request.get_json()
    if not data or 'key' not in data or 'object' not in data:
        return jsonify({'status': 'error', 'message': '请提供key和object'}), 400
    
    key = data['key']
    obj = data['object']
    timeout = data.get('timeout', RedisConfig.CACHE_DEFAULT_TIMEOUT)
    
    success = RedisUtils.set_object(key, obj, timeout)
    return jsonify({
        'status': 'success' if success else 'error',
        'message': '存储成功' if success else '存储失败',
        'key': key,
        'object_type': type(obj).__name__,
        'timeout': timeout
    })


@redis_example_bp.route('/redis/object/get', methods=['GET'])
def redis_object_get():
    """获取对象"""
    key = request.args.get('key')
    if not key:
        return jsonify({'status': 'error', 'message': '请提供key'}), 400
    
    obj = RedisUtils.get_object(key)
    return jsonify({
        'status': 'success',
        'key': key,
        'object': obj,
        'object_type': type(obj).__name__ if obj is not None else None
    })


@redis_example_bp.route('/redis/session/set', methods=['POST'])
def redis_session_set():
    """设置用户会话"""
    data = request.get_json()
    if not data or 'user_id' not in data or 'session_data' not in data:
        return jsonify({'status': 'error', 'message': '请提供user_id和session_data'}), 400
    
    user_id = data['user_id']
    session_data = data['session_data']
    
    success = RedisUtils.cache_user_session(user_id, session_data)
    return jsonify({
        'status': 'success' if success else 'error',
        'message': '会话缓存成功' if success else '会话缓存失败',
        'user_id': user_id,
        'session_data': session_data
    })


@redis_example_bp.route('/redis/session/get', methods=['GET'])
def redis_session_get():
    """获取用户会话"""
    user_id = request.args.get('user_id')
    if not user_id:
        return jsonify({'status': 'error', 'message': '请提供user_id'}), 400
    
    try:
        user_id = int(user_id)
    except ValueError:
        return jsonify({'status': 'error', 'message': 'user_id必须是整数'}), 400
    
    session_data = RedisUtils.get_user_session(user_id)
    return jsonify({
        'status': 'success',
        'user_id': user_id,
        'session_data': session_data,
        'exists': session_data is not None
    })


@redis_example_bp.route('/redis/session/clear', methods=['DELETE'])
def redis_session_clear():
    """清除用户会话"""
    user_id = request.args.get('user_id')
    if not user_id:
        return jsonify({'status': 'error', 'message': '请提供user_id'}), 400
    
    try:
        user_id = int(user_id)
    except ValueError:
        return jsonify({'status': 'error', 'message': 'user_id必须是整数'}), 400
    
    success = RedisUtils.clear_user_session(user_id)
    return jsonify({
        'status': 'success' if success else 'error',
        'message': '会话清除成功' if success else '会话清除失败',
        'user_id': user_id
    })